const async = require('async');
const ObjectID = require('mongodb').ObjectID;
const orderCode = require('yi-order-number');

module.exports = {
    open: false,
    description: '购物车结算价格',
    handler(req, res, next) {
        let doc = req.body;

        req.mongo.collection("coupon").find({_id:{$in:doc.couponIds}}).toArray((e7,r7)=>{
            if(e7) return res.reply({code:30001,message:'优惠券信息异常请重试'});

            req.mongo.collection("cart").aggregate([
                {
                    $match: {_id: {$in: doc.cartIds}}
                },
                {
                    $lookup: {
                        from: "store",
                        localField: "storeId",
                        foreignField: "_id",
                        as: "store"
                    }
                },
                {
                    $unwind: "$store",
                },
                {
                    $lookup: {
                        from: "goods",
                        localField: "goodsId",
                        foreignField: "_id",
                        as: "goods"
                    }
                },
                {
                    $unwind: "$goods",
                },
                {
                    $lookup: {
                        from: "coupon",
                        localField: "couponId",
                        foreignField: "_id",
                        as: "coupon"
                    }
                }
            ]).toArray((e0, r0) => {

                let authInfo = req.context || req.context.authInfo;
                if (!req.context || !req.context.authInfo) {
                    return res.err.unauthorized();
                }
                authInfo = authInfo.authInfo;
                let id = ObjectID(authInfo._id);

                let uPid = new ObjectID();
                let orderType = 0;
                let orderAmount = 0;
                let orderPayAmount = 0;

                let sPids = [];
                let storeIds = [];

                let orders = [];
                let orderItems = [];

                let orderNo = orderCode.getOrderNo();

                r0.forEach((cart) => {
                    let newStoreId = cart.storeId.toString();

                    if (storeIds.indexOf(newStoreId) === -1) {
                        let sPid = new ObjectID();
                        storeIds.push(newStoreId);
                        sPids.push(sPid);
                        orderType = cart.store.type;

                        let order = {
                            _id: sPid,
                            mallId: cart.mallId,
                            storeId: cart.storeId,
                            orderType: cart.store.type,
                            orderNo: orderNo,
                            orderStatus: "待付款",
                            orderAmount:0,
                            orderPayAmount:0
                        };

                        order.orderAmount += (cart.goods.actualPrice)*cart.buyCount;
                        order.orderPayAmount += (cart.goods.actualPrice)*cart.buyCount;

                        orders.push(order);

                        orderAmount += (cart.goods.actualPrice) * cart.buyCount;
                        orderPayAmount += (cart.goods.actualPrice) * cart.buyCount;

                        let orderItem = {
                            _id: new ObjectID(),
                            sPid: sPid,
                            uPid: uPid,
                            orderType: cart.goods.type,
                            goodsId: cart.goods._id,
                            name: cart.goods.name,
                            model: cart.goods.model,
                            modelEx: cart.goods.modelEx,
                            goodsCode: cart.goods.goodsCode,
                            color: cart.goods.color,
                            measure: cart.goods.measure,
                            salePrice: cart.goods.salePrice,
                            actualPrice: cart.goods.actualPrice,
                            label: cart.goods.label,
                            image: cart.goods.image,
                            quantity: cart.buyCount
                        };

                        orderItems.push(orderItem);

                    } else {
                        orderAmount += (cart.goods.actualPrice) * cart.buyCount;
                        orderPayAmount += (cart.goods.actualPrice) * cart.buyCount;

                        orders[storeIds.indexOf(newStoreId)].orderAmount += (cart.goods.actualPrice)*cart.buyCount;
                        orders[storeIds.indexOf(newStoreId)].orderPayAmount += (cart.goods.actualPrice)*cart.buyCount;

                        let orderItem = {
                            _id: new ObjectID(),
                            sPid: sPids[storeIds.indexOf(newStoreId)],
                            uPid: uPid,
                            orderType: cart.goods.type,
                            goodsId: cart.goods._id,
                            name: cart.goods.name,
                            model: cart.goods.model,
                            modelEx: cart.goods.modelEx,
                            goodsCode: cart.goods.goodsCode,
                            color: cart.goods.color,
                            measure: cart.goods.measure,
                            salePrice: cart.goods.salePrice,
                            actualPrice: cart.goods.actualPrice,
                            label: cart.goods.label,
                            image: cart.goods.image,
                            quantity: cart.buyCount
                        };
                        orderItems.push(orderItem);
                    }

                });

                let payAmount = orderPayAmount;

                orders.forEach((order)=>{
                    let couponId = null;
                    let facevalue = null;
                    r7.forEach((coupon)=>{
                        coupon.storeIds.forEach((storeId)=>{
                            if(storeId.toString()===order.storeId.toString()){
                                couponId = coupon._id;
                                facevalue = coupon.facevalue;
                            }
                        });
                    });
                    if(couponId){
                        order.couponId = couponId;
                        order.facevalue = facevalue;
                        order.orderPayAmount = order.orderPayAmount-facevalue;
                        payAmount = payAmount - facevalue;
                    }
                });

                let userOrder = {
                    _id: uPid,
                    userId: id,
                    userOrderNo: orderNo,
                    orderType: orderType,
                    orderStatus: "待支付",
                    orderAmount: orderPayAmount,
                    couponIds: doc.couponIds,
                    orderPayAmount: payAmount
                };

                async.auto([
                        callback => req.mongo.collection('order').insertMany(orders, callback),
                        callback => req.mongo.collection('orderItem').insertMany(orderItems, callback),
                        callback => req.mongo.collection('order').insert(userOrder, callback)
                    ],
                    (e3, r3) => {
                        if (e3) return res.err.mongoError(e3);
                        req.mongo.collection('order').aggregate([
                            {$match: {_id: uPid}},
                            {
                                $lookup: {
                                    from: "orderItem",
                                    localField: "_id",
                                    foreignField: "uPid",
                                    as: "orderItems"
                                }
                            }
                        ]).toArray((e4, r4) => {
                            if (e4) return res.err.mongoError(e4);
                            return res.reply({code: 0, message: '购物车结算', data: r4});
                        });
                    });
            });
        });
    }
};
